package services;

import br.com.caelum.vraptor.ioc.Component;
import models.ProductImportList;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.*;

@Component
public class ProductImportService {

    public final static byte XML = 1;
    public final static byte SPRING = 2;

    public ProductImportList parseXml(InputStream stream) throws JAXBException{

        JAXBContext jaxbContext = JAXBContext.newInstance(ProductImportList.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        ProductImportList products = (ProductImportList) jaxbUnmarshaller.unmarshal(stream);

        return products;
    }

    /*
    public void serialize(ProductImportList list) throws JAXBException{
        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(ProductImportList.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(list, file);
    }
    */

    public ProductImportList readSpring(InputStream stream){
        //FileSystemResource
        //InputStreamResource
        String tempFile = System.getProperty("java.io.tmpdir") + File.separator + "tempFile";

        saveStream(stream, tempFile);

        Resource xmlResource = new FileSystemResource(tempFile);
        BeanFactory factory = new XmlBeanFactory(xmlResource);
        ProductImportList products = (ProductImportList)factory.getBean("products");

        return products;
    }

    private void saveStream(InputStream inputStream, String fileName) {
        try{
            OutputStream out = new FileOutputStream(new File(fileName));

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = inputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.flush();
            out.close();
        } catch(IOException ex){

        }
    }
}
